package com.zyk.scaffold.gateway.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class RequestLoggingFilter implements GlobalFilter, Ordered {

    private static final Log log = LogFactory.getLog(RequestLoggingFilter.class);
    private static final String logFormat = "Method:{%s} Host:{%s} Path:{%s} Query:{%s} executeTime:{%d}ms";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Long startTime = System.currentTimeMillis();
        ServerHttpRequest request=exchange.getRequest();
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            if (startTime != null) {
                Long executeTime = (System.currentTimeMillis() - startTime);
                String info = String.format(logFormat,
                        request.getMethod().name(),
                        request.getURI().getHost(),
                        request.getURI().getPath(),
                        request.getQueryParams(),
                        executeTime);
                log.info(info);
                log.info(request.getURI().toString());
            }
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
